package com.yanqu.road.server.push.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.server.helper.ChatHelper;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.entity.enums.eErrorCode;
import com.yanqu.road.entity.util.ResponseUtil;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.DataUploadInfoMgr;
import com.yanqu.road.queue.PushQueue;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.http.HttpHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;

/**
 * @author duli
 * @version 1.0
 * @date 2020/8/31 17:50
 * @Description 数据上报
 */
public class PushHolder {
    protected static Logger log = LogManager.getLogger(PushHolder.class.getName());
    private static RandomHelper random = new RandomHelper();
    private JSONObject jsonObject=new JSONObject();
    private static final int pollSize = 200;

    /**
     * 线程池执行消息队列
     */
    public void execute() {
        if (!DataUploadInfoMgr.isAllowUpload()) {
            return;
        }
        String result = "";
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "application/json");
            JSONArray jsonArray = PushQueue.poll(pollSize);
            if (!jsonArray.isEmpty()) {
                jsonObject.put("batch",jsonArray);
                log.info("PushQueue poll size:"+jsonArray.size());
                String url =AppKeyMgr.getPlatformBaseUrl()+"/user/report/batchReport?"+getQuery();
                log.info("PushQueue url:{}", url);
                result = HttpHelper.doPostJsonTimeOut(url, jsonObject.toString(), "UTF-8", headerMap);
            }

        } catch (Exception e) {
            log.error("命令[批量上报]处理异常...", e);
        } finally {
            if (!result.isEmpty()) {
                wrapperResult(result);
            }
        }
    }

    private String getQuery() {
        SortedMap<String, String> paramMap = new TreeMap<>();
        paramMap.put("appID", AppKeyMgr.getAndroidAppId());
        paramMap.put("channelID", AppKeyMgr.getPlatformChannelId());
        String sign = SignHelper.getSign(paramMap,AppKeyMgr.getAndroidAppSecret());
        paramMap.put("sign", sign);
        return ChatHelper.getUrlData(paramMap);
    }

    public static int currentTimeSeconds() {
        return (int) (System.currentTimeMillis() / 1000);
    }

    private void wrapperResult(String result) {
        try {
            ResponseUtil responseUtil = JSON.parseObject(result, ResponseUtil.class);
            if (responseUtil.getState()== 1) {
                log.info("push success,send message is" + jsonObject);
                log.info("call back message is" + result);
            } else {
                log.info("push faild,send message is" + jsonObject);
                log.info("call back message is" + result);
            }
        } catch (Exception e) {
            log.error(eErrorCode.CALL_BACK_ERROR.getMessage() + ":" + jsonObject);
            log.error("call back message is" + result);
        }

    }


}
